// import { uploadArticleImage } from '@/services/api/api-article';
import { renewOSS } from '@/services/api/api-aliyun';
import { isDev } from '@/utils/dev';
import { getToken } from '@/utils/token';
import { getUUID } from '@/utils/uuid';
import { DeleteOutlined, FileSearchOutlined } from '@ant-design/icons';
import { Button, message } from 'antd';
import moment from 'moment';
import React, { useEffect } from 'react';
const OSS = require('ali-oss');

interface GdrmTinyMceProps {
  accountId?: string;
  organizationName?: string;
  defaultContent?: string;
  action: string;
  onInit?: () => void;
  value?: string | undefined;
  onChange?: (value: string) => void;
}

const GdrmTinyMce: React.FC<GdrmTinyMceProps> = ({
  accountId,
  organizationName,
  defaultContent,
  action,
  onInit,
  value,
  onChange,
}) => {
  const tinyID = 'tinyID';

  useEffect(() => {
    tinyMCE.init({
      selector: '#' + tinyID,
      height: 790,
      resize: true,
      language: 'zh_CN',
      plugins:
        'tpImportword tpIndent2em tpLayout  axupimgs directionality table fullscreen preview quickbars wordcount image',
      menubar: false,
      toolbar:
        'tpImportword tpIndent2em tpLayout | undo redo |fontsizeselect  alignleft aligncenter alignright alignjustify |  image |  fullscreen preview wordcount',
      fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
      statusbar: true,
      //statusbar 左下角
      elementpath: false,
      contextmenu: 'table',
      placeholder: '请输入...',
      //快速栏插入工具栏
      quickbars_selection_toolbar: false,
      quickbars_insert_toolbar: false,
      //图片对话框中报送标签开关
      image_advtab: false,
      image_uploadtab: true,
      visual_anchor_class: '',
      automatic_uploads: true,
      resize_img_proportional: false,
      images_upload_handler: function (blobInfo: any, succFun: any, failFun: any, progress: any) {
        return new Promise((resolve, reject) => {
          renewOSS().then((response) => {
            if (response.code == 0) {
              const headers = {
                'Content-Disposition': 'attachment;',
              };
              const multipartUploadOptions = {
                callback: {
                  url: action,
                  body:
                    '{"bucket":${bucket}, "object":${object}, "etag":${etag}, "size":${size}, "mimeType":${mimeType}, "satoken":"' +
                    getToken() +
                    '"}',
                  contentType: 'application/json',
                },
                progress: (index: number, cpt: any, res: any) => {
                  progress(Math.round(index * 100).toFixed(2));
                },
                headers,
              };
              const OSSData = {
                host: `${!isDev() ? 'cqgdrm-xtbs' : 'cqgdrm-xtbs-test'}.oss-cn-hangzhou.aliyuncs.com`,
                accessKeyId: response.data.accessKeyId,
                accessKeySecret: response.data.accessKeySecret,
                stsToken: response.data.securityToken,
                region: 'oss-cn-hangzhou',
                bucket: !isDev() ? 'cqgdrm-xtbs' : 'cqgdrm-xtbs-test',
              };

              const client = new OSS({
                region: 'oss-cn-hangzhou',
                accessKeyId: OSSData.accessKeyId,
                accessKeySecret: OSSData.accessKeySecret,
                stsToken: OSSData.stsToken,
                refreshSTSToken: async () => {
                  const response = await renewOSS();
                  return {
                    accessKeyId: response.data.accessKeyId,
                    accessKeySecret: response.data.accessKeySecret,
                    stsToken: response.data.securityToken,
                  };
                },
                // 刷新临时访问凭证的时间间隔，单位为毫秒。
                refreshSTSTokenInterval: 300000,
                bucket: OSSData.bucket,
              });

              client
                .multipartUpload(
                  `${organizationName}/${moment().format('YYYY-MM-DD')}/${getUUID()}.png`,
                  new Blob([blobInfo.blob()]),
                  multipartUploadOptions,
                )
                .then((response: any) => {
                  console.log('======', response);
                  if (response.data.Status == 'ok') {
                    succFun(response.data.url);
                  } else {
                    failFun('上传失败');
                  }
                })
                .catch((e) => {
                  failFun('上传失败');
                });
            }
          });
        });
      },
      content_css: 'default',
      content_style:
        'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }.read-write-plain-text-only{-webkit-user-modify: read-write-plaintext-only;}.word-mark-error{color:rgb(255,255,255);text-decoration:none;background-color:rgb(228,60,48);cursor:pointer}.word-mark-error:hover{color:rgb(255,255,255)}.word-mark-error-highlight{color:rgb(255,255,255);font-size:22px;text-decoration:none;background-color:rgb(251,194,29);cursor:pointer}.word-mark-error-highlight:hover{color:rgb(255,255,255)}.word-mark-right{color:rgb(255,255,255);text-decoration:none;background-color:rgb(13,188,121);cursor:pointer}.word-mark-right:hover{color:rgb(255,255,255)}.word-mark-right-highlight{color:rgb(255,255,255);font-size:22px;text-decoration:none;background-color:rgb(41,155,73);cursor:pointer}.word-mark-right-highlight:hover{color:rgb(255,255,255)}.read-write-plain-text-only{-webkit-user-modify:read-write-plaintext-only}.split-row-select-active{background-color:#e6f7ff}',
      setup(editor: any) {
        editor.on('input', function (e) {
          //当用户输入的时候调用的事件函数
          onChange!(tinyMCE.editors[tinyID].getContent());
        });
        editor.on('change', function (e) {
          //当用户输入的时候调用的事件函数
          onChange!(tinyMCE.editors[tinyID].getContent());
        });
      },
      init_instance_callback: (editor: any) => {
        onInit!();
        if (defaultContent) {
          editor.setContent('');
          editor.insertContent(defaultContent);
          editor.shortcuts.remove('Ctrl+Y');
          editor.shortcuts.remove('Command+Y');
          editor.shortcuts.remove('Ctrl+Shift+Z');
          editor.shortcuts.remove('Command+Shift+Z');
          onChange!(editor.getContent());
        }
        tinyMCE.EditorManager.add(editor);
      },
    });

    return () => {
      tinyMCE.editors[tinyID].destroy();
    };
  }, []);

  useEffect(() => {
    if (defaultContent) {
      value = defaultContent;
      tinyMCE.editors[tinyID].insertContent(defaultContent);
    }
  }, [defaultContent]);

  return (
    <>
      <div>
        <Button
          type="primary"
          icon={<FileSearchOutlined />}
          key="import"
          onClick={() => {
            tinyMCE.EditorManager.get(tinyID).execCommand('mceTpImportword');
          }}
        >
          导入Word文档（.docx）
        </Button>
        <Button
          icon={<DeleteOutlined />}
          style={{ position: 'absolute', right: 0 }}
          key="clear"
          danger
          onClick={() => {
            tinyMCE.EditorManager.get(tinyID).setContent('');
            message.success('清空成功');
          }}
        >
          清空
        </Button>
      </div>
      <div
        style={{
          marginTop: 10,
        }}
      >
        <textarea id={tinyID} />
      </div>
    </>
  );
};

export default GdrmTinyMce;
